<template>
  <div>
    <base-table
      ref="table"
      :page-config="{
        pageSize: 5,
        pageNo: 1,
      }"
      :page-sizes="[5, 10, 15, 20, 50]"
      :search-params="searchParams"
      :columns="columnsAction"
      :async-fc="pageMaterialsApi"
    >
      <template #tableHeader>
        <t-button @click="insert">{{ t('components.commonTable.insert') }}</t-button>
      </template>
    </base-table>
    <t-dialog v-model:visible="modalOpen" width="45%" @confirm="onModalSubmit">
      <t-form ref="submitFormRef" style="width: 100%" :rules="rules" :data="submitForm" label-align="top">
        <t-row style="width: 100%" :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item :label="'药材名称'" name="name">
              <t-input v-model="submitForm.name" :placeholder="'请输入药材名称'" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="'英文名'" name="nameEn">
              <t-input v-model="submitForm.nameEn" :placeholder="'请输入英文名'" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="'产地'" name="origin">
              <t-input v-model="submitForm.origin" :placeholder="'请输入产地'" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="'封面图'" name="cover">
              <common-upload
                v-model:value="submitForm.cover"
                :value-type="'data'"
                :limit="1"
                :tip="'请上传封面图'"
              ></common-upload>
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="'介绍'" name="introduction">
              <rich-editor v-model="submitForm.introduction" height="300px" placeholder="请输入文章内容..." />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="'备注'" name="remark">
              <t-textarea v-model="submitForm.remark" :placeholder="'请输入备注'" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-dialog>
    <picture-list
      :visible="showPictures"
      :title="'药材图集'"
      :images="picturesInfo.pictures"
      :ids="picturesInfo.ids"
      @close="closePictures"
    />
    <t-dialog v-model:visible="uploadPictures">
      <common-upload v-model:value="tempImage" :value-type="'json'" :limit="5" :tip="'请上传药材图集'"></common-upload>
      <template #footer>
        <t-button @click="uploadPictures = false">取消</t-button>
        <t-button theme="primary" @click="onUploadPictures">确定</t-button>
      </template>
    </t-dialog>
    <taboo
      v-model:visible="showTabooModel"
      title="药材禁忌"
      :contraindicated="contraindicated"
      @confirm="refresh"
    ></taboo>
  </div>
</template>
<script setup lang="ts">
import {
  Button,
  DialogPlugin,
  FormInstanceFunctions,
  Icon,
  Image,
  Link,
  MessagePlugin,
  Select,
  Space,
  Tag,
} from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';

import {
  addPicturesApi,
  deleteEfficacyApi,
  deleteMaterialsApi,
  getAllEfficacyApi,
  getPicturesApi,
  insertMaterialsApi,
  pageMaterialsApi,
  updateEfficacyApi,
  updateMaterialsApi,
} from '@/api/medicinal';
import baseTable from '@/components/base-table/index.vue';
import commonUpload from '@/components/common-upload/index.vue';
import RichEditor from '@/components/rich-editor/index.vue';
import { t } from '@/locales';
import { FileItem } from '@/types/interface';

import { getColumns, getRules, getSearchParams } from './constants';
import pictureList from './modules/pictures.vue';
import taboo from './modules/taboo.vue';

// 提交表单
const submitForm = ref<any>({});
// 功效列表
const efficacyList = ref([]);
// 弹窗
const modalOpen = ref(false);
// 表单提交
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<_TableInstanceFunctions>(null);
// 选中状态
const rowSelectState = ref<Record<number, boolean>>({});
// 选中的功效
const selectedEfficacy = ref<Record<number, any[]>>({});
// 图集组件
const showPictures = ref(false);
interface _pInfo {
  id: number;
  name: string;
  pictures: string[];
  ids: number[];
}
const picturesInfo = ref<_pInfo>({
  id: null,
  name: '',
  pictures: [],
  ids: [],
});
const uploadPictures = ref(false);

const tempImage = ref<FileItem[]>([]);
const onUploadPictures = async () => {
  if (!tempImage.value.length) {
    MessagePlugin.warning('请上传图片');
    return;
  }
  picturesInfo.value.pictures = tempImage.value.map((item) => item.data);
  await addPicturesApi({
    materialId: picturesInfo.value.id,
    pictures: picturesInfo.value.pictures,
  });
  uploadPictures.value = false;
  table.value?.onSearch();
};
const uploadLayer = (row: any) => {
  uploadPictures.value = true;
  picturesInfo.value.name = row.name;
  picturesInfo.value.id = row.id;
  picturesInfo.value.pictures = [];
  picturesInfo.value.ids = [];
  tempImage.value = [];
};
const closePictures = () => {
  showPictures.value = false;
  table.value?.onSearch();
};

const searchParams = computed(() => getSearchParams());
const rules = computed(() => getRules());
const columns = computed(() => getColumns());

const handleAddEfficacy = (row: any) => {
  rowSelectState.value[row.id] = true;
  selectedEfficacy.value[row.id] = row.efficacy.map((item: { value: string }) => item.value);
};

const columnsAction = computed(() =>
  columns.value.concat([
    {
      title: '禁忌',
      align: 'center',
      colKey: 'taboo',
      cell: (h, { row }) =>
        h(
          Button,
          {
            size: 'small',
            theme: 'warning',
            icon: () => h(Icon, { name: 'browse' }, ''),
            onClick: () => {
              contraindicated.value = {
                medicinalId: row.id,
                taboo: {
                  id: row.taboo?.id,
                  people: row.taboo?.contraindicatedPeople,
                  matters: row.taboo?.contraindicatedMatters,
                },
              };
              showTabooModel.value = true;
            },
          },
          () => '查看',
        ),
    },
    {
      title: '图集',
      align: 'center',
      width: 284,
      colKey: 'pictures',
      cell: (h, { row }) => {
        return h(Image, {
          src: row.defaultPicture,
          style: {
            width: '284px',
            height: '160px',
          },
          gallery: true,
          overlayContent: () => {
            return h(
              'div',
              {
                style: {
                  background: 'rgba(0,0,0,.4)',
                  color: '#fff',
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                },
              },
              [
                h(
                  Button,
                  {
                    size: 'small',
                    onClick: () => {
                      picturesInfo.value.name = row.name;
                      getPicturesApi(row.id).then((res) => {
                        picturesInfo.value.pictures = res.map((item: { image: string }) => item.image);
                        picturesInfo.value.ids = res.map((item: { id: number }) => item.id);
                        if (picturesInfo.value.pictures.length === 0) {
                          MessagePlugin.warning('暂无图集');
                          return;
                        }
                        showPictures.value = true;
                      });
                    },
                  },
                  () => '预览',
                ),
                h(
                  Button,
                  {
                    size: 'small',
                    onClick: () => {
                      uploadLayer(row);
                    },
                  },
                  () => '上传',
                ),
              ],
            );
          },
          overlayTrigger: 'hover',
        });
      },
    },
    {
      align: 'center',
      width: 200,
      colKey: 'efficacy',
      title: '功效',
      cell: (h, { row }) =>
        h(
          Space,
          {
            direction: 'vertical',
            size: 'small',
            align: 'start',
          },
          () => [
            row.efficacy.length !== 0
              ? h(
                  Space,
                  {
                    direction: 'vertical',
                    size: 'small',
                    align: 'start',
                    class: 'tag-block light',
                  },
                  () => [
                    row.efficacy.map((item: { value: string; label: string }) =>
                      h(
                        Tag,
                        {
                          size: 'small',
                          theme: 'success',
                          variant: 'light',
                          closable: true,
                          maxWidth: 200,
                          title: item.label,
                          onClose: async () => {
                            await deleteEfficacyApi(row.id, Number(item.value));
                            MessagePlugin.success('删除成功');
                            table.value.onSearch();
                          },
                        },
                        () => item.label,
                      ),
                    ),
                  ],
                )
              : '',
            rowSelectState.value[row.id]
              ? h(Select, {
                  options: efficacyList.value.map((item) => {
                    return {
                      value: item.value,
                      label: item.label,
                    };
                  }),
                  multiple: true,
                  size: 'small',
                  minCollapsedNum: 1,
                  modelValue: selectedEfficacy.value[row.id],
                  panelBottomContent: () =>
                    h(
                      Button,
                      {
                        size: 'small',
                        style: { margin: '10px' },
                        onClick: () => {
                          updateEfficacy(row.id, selectedEfficacy.value[row.id]);
                        },
                      },
                      () => '确定',
                    ),
                  onChange: async (value: any) => {
                    selectedEfficacy.value[row.id] = value;
                  },
                })
              : h(
                  Tag,
                  {
                    size: 'small',
                    variant: 'light',
                    style: {
                      cursor: 'pointer',
                    },
                    icon: () => h(Icon, { name: 'add' }),
                    maxWidth: 200,
                    onClick: () => {
                      handleAddEfficacy(row);
                    },
                  },
                  () => '添加功效',
                ),
          ],
        ),
    },
    {
      title: '备注',
      ellipsis: true,
      align: 'center',
      colKey: 'remark',
    },
    {
      align: 'left',
      fixed: 'right',
      width: 160,
      colKey: 'op',
      title: t('components.commonTable.operation'),
      cell: (h, { row }) =>
        h(
          Space,
          {
            split: 'line',
          },
          () => [
            h(
              Link,
              {
                theme: 'primary',
                underline: false,
                onClick: () => {
                  submitForm.value = row;
                  modalOpen.value = true;
                },
              },
              () => t('components.commonTable.edit'),
            ),
            h(
              Link,
              {
                theme: 'danger',
                underline: false,
                onClick: () => {
                  const confirmDialog = DialogPlugin.confirm({
                    header: t('components.commonTable.tips'),
                    body: t('components.commonTable.deleteConfirm'),
                    confirmBtn: {
                      content: t('components.commonTable.submit'),
                      theme: 'primary',
                      loading: false,
                    },
                    cancelBtn: {
                      content: t('components.commonTable.cancel'),
                      theme: 'default',
                      loading: false,
                    },
                    theme: 'warning',
                    onConfirm: async () => {
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submitting'), loading: true },
                      });
                      await deleteMaterialsApi(row.id);
                      MessagePlugin.success(t('components.commonTable.deleteSuccess'));
                      table.value.onSearch();
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submit'), loading: false },
                      });
                      confirmDialog.hide();
                    },
                  });
                },
              },
              () => t('components.commonTable.delete'),
            ),
          ],
        ),
    },
  ]),
);

const insert = () => {
  modalOpen.value = true;
  submitForm.value = {};
};

onMounted(async () => {
  const res = await getAllEfficacyApi();
  efficacyList.value = res;
});

const refresh = () => {
  table.value.onSearch();
};

const updateEfficacy = async (id: number, selectedEfficacy: string[]) => {
  const params = {
    materialId: id,
    efficacyIds: selectedEfficacy.map((item: string) => Number(item)),
  };
  await updateEfficacyApi(params);
  table.value.onSearch();
  rowSelectState.value = {};
  MessagePlugin.success('修改成功！');
};

/**
 * 提交表单
 */
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid === true) {
    if (submitForm.value.id) {
      await updateMaterialsApi(submitForm.value);
    } else {
      await insertMaterialsApi(submitForm.value);
    }
    MessagePlugin.success('操作成功！');
    modalOpen.value = false;
    table.value.onSearch();
  }
};
/** 药材禁忌 */
const showTabooModel = ref(false);
const contraindicated = ref({});
</script>

<style lang="less" scoped>
:deep(.t-dialog) {
  .t-dialog__body {
    max-height: calc(90vh - 200px);
    overflow-y: auto;
  }

  .t-form {
    .t-form__item {
      padding: 0 0 24px 0;
      margin-bottom: 0;

      &:last-child {
        padding-bottom: 0;
      }
    }

    .t-radio-group {
      display: flex;
      gap: 32px;
    }
  }
}

:deep(.t-table) {
  .t-avatar {
    width: 40px;
    height: 40px;
    font-size: 16px;
    background: #e3e6eb;
  }
}
</style>
